package com.chen.core.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chen.core.dal.BaseDO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class DefaultFillHandler implements MetaObjectHandler {
    //插入策略
    @Override
    public void insertFill(MetaObject metaObject) {
        //判断对象是否为空以及对象是不是baseDo
        if (ObjectUtil.isNotNull(metaObject)&&
               metaObject.getOriginalObject()instanceof BaseDO) {
            BaseDO baseDO =(BaseDO) metaObject.getOriginalObject();
            //插入创建时间字段
            if(ObjectUtil.isNull(baseDO.getCreateTime())){
                baseDO.setCreateTime(LocalDateTime.now());
            }
            //插入更新时间字段
            if(ObjectUtil.isNull(baseDO.getUpdateTime())){
                baseDO.setUpdateTime(LocalDateTime.now());
            }
            //todo 字段的创建者设置
            //设置创建者
            if(ObjectUtil.isNull(baseDO.getCreator())){
                baseDO.setCreator("1");
            }

            //设置更新者
            if(ObjectUtil.isNull(baseDO.getUpdater())){
                baseDO.setUpdater("1");
            }
        }
    }
    //更新策略
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if(ObjectUtil.isNull(updateTime)){
        setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
        }

        Object updater = getFieldValByName("updater", metaObject);
        if(ObjectUtil.isNull(updater)){
            setFieldValByName("updater", "1",metaObject);
        }

    }
}
